<?php


namespace app\utils;

use AlibabaCloud\SDK\Ocrapi\V20210707\Ocrapi;
use app\lib\exception\AliyunApiException;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;

use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Ocrapi\V20210707\Models\RecognizeBasicRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class AliyunIDCard
{

    /**
     * 使用AK&SK初始化账号Client
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @return Ocrapi Client
     */
    public static function createClient($accessKeyId, $accessKeySecret)
    {
        $config = new Config([
            // 必填，您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 必填，您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Ocrapi($config);
    }

    public function getIDCard($url){
        // 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/311677.html
        $client = self::createClient(env('aliyun.ak'),env('aliyun.sk'));
        $recognizeBasicRequest = new RecognizeBasicRequest([
            "outputFigure" => true,
            "url" => $url,
            "outputQualityInfo" => true
        ]);
        try {
            // 复制代码运行请自行打印 API 的返回值
            $response = $client->recognizeBasicWithOptions($recognizeBasicRequest, new RuntimeOptions([]));
        } catch (Exception $error) {
           throw new AliyunApiException($error->getMessage());
        }

        return json_decode($response->body->data, true);
    }
}